/**
 * 语音识别工具类
 * 支持Web Speech API和移动端语音识别
 */

class SpeechRecognitionManager {
  constructor() {
    this.recognition = null
    this.isSupported = false
    this.isListening = false
    this.isInitialized = false
    this.eventListeners = new Map()
    
    // 语音命令映射
    this.commandMappings = {
      // 基础交互
      '你好': ['hello', 'hi', '你好', 'hi', 'hello'],
      '再见': ['bye', 'goodbye', '再见', '拜拜'],
      
      // 宠物操作
      '喂食': ['feed', 'food', 'eat', '喂食', '吃饭', '喂', '食'],
      '玩耍': ['play', 'game', 'fun', '玩耍', '玩', '游戏'],
      '休息': ['rest', 'sleep', 'nap', '休息', '睡觉', '睡'],
      '抱抱': ['hug', 'cuddle', '抱抱', '抱', '拥抱'],
      
      // 状态查询
      '状态': ['status', 'how', '状态', '怎么样', '如何'],
      '心情': ['mood', 'feeling', '心情', '感觉'],
      '饥饿': ['hungry', 'hunger', '饥饿', '饿'],
      '精力': ['energy', 'tired', '精力', '累'],
      
      // 设置相关
      '设置': ['settings', 'config', '设置', '配置'],
      '隐藏': ['hide', 'disappear', '隐藏', '消失'],
      '显示': ['show', 'appear', '显示', '出现'],
      
      // 功能相关
      '帮助': ['help', 'assist', '帮助', '帮忙'],
      '时间': ['time', 'clock', '时间', '几点'],
      '天气': ['weather', 'weather', '天气', '气象']
    }
    
    this.init()
  }
  
  /**
   * 初始化语音识别
   */
  init() {
    try {
      // 检查浏览器支持
      if (typeof webkitSpeechRecognition !== 'undefined') {
        this.recognition = new webkitSpeechRecognition()
        this.isSupported = true
      } else if (typeof SpeechRecognition !== 'undefined') {
        this.recognition = new SpeechRecognition()
        this.isSupported = true
      } else {
        // 静默处理不支持的情况，避免控制台警告
        this.isSupported = false
        this.isInitialized = true // 标记为已初始化，避免重复尝试
        return
      }
      
      // 配置语音识别参数
      this.setupRecognition()
      this.isInitialized = true
      
      console.log('语音识别初始化成功')
    } catch (error) {
      console.error('语音识别初始化失败:', error)
      this.isSupported = false
      this.isInitialized = true // 标记为已初始化，避免重复尝试
    }
  }
  
  /**
   * 配置语音识别参数
   */
  setupRecognition() {
    if (!this.recognition) return
    
    // 基础配置
    this.recognition.continuous = false
    this.recognition.interimResults = false
    this.recognition.lang = 'zh-CN'
    this.recognition.maxAlternatives = 3
    
    // 事件监听
    this.recognition.onstart = () => {
      this.isListening = true
      this.emit('recognition-start')
    }
    
    this.recognition.onresult = (event) => {
      this.handleRecognitionResult(event)
    }
    
    this.recognition.onerror = (event) => {
      this.handleRecognitionError(event)
    }
    
    this.recognition.onend = () => {
      this.isListening = false
      this.emit('recognition-end')
    }
  }
  
  /**
   * 处理识别结果
   */
  handleRecognitionResult(event) {
    const results = event.results
    const transcript = results[0][0].transcript.toLowerCase().trim()
    const confidence = results[0][0].confidence
    
    console.log('语音识别结果:', { transcript, confidence })
    
    // 解析命令
    const command = this.parseCommand(transcript)
    
    this.emit('recognition-result', {
      transcript,
      confidence,
      command,
      timestamp: Date.now()
    })
  }
  
  /**
   * 处理识别错误
   */
  handleRecognitionError(event) {
    console.error('语音识别错误:', event.error)
    
    this.emit('recognition-error', {
      error: event.error,
      timestamp: Date.now()
    })
  }
  
  /**
   * 解析语音命令
   */
  parseCommand(transcript) {
    for (const [action, keywords] of Object.entries(this.commandMappings)) {
      for (const keyword of keywords) {
        if (transcript.includes(keyword)) {
          return {
            action,
            keyword,
            confidence: 1.0,
            originalText: transcript
          }
        }
      }
    }
    
    return {
      action: 'unknown',
      keyword: '',
      confidence: 0,
      originalText: transcript
    }
  }
  
  /**
   * 开始语音识别
   */
  startListening() {
    if (!this.isSupported || !this.isInitialized) {
      this.emit('recognition-error', {
        error: 'not_supported',
        message: '语音识别不支持或未初始化'
      })
      return false
    }
    
    if (this.isListening) {
      console.log('语音识别已在进行中')
      return false
    }
    
    try {
      this.recognition.start()
      return true
    } catch (error) {
      console.error('启动语音识别失败:', error)
      this.emit('recognition-error', {
        error: 'start_failed',
        message: error.message
      })
      return false
    }
  }
  
  /**
   * 停止语音识别
   */
  stopListening() {
    if (!this.isSupported || !this.isListening) {
      return false
    }
    
    try {
      this.recognition.stop()
      return true
    } catch (error) {
      console.error('停止语音识别失败:', error)
      return false
    }
  }
  
  /**
   * 获取支持的语言列表
   */
  getSupportedLanguages() {
    return [
      { code: 'zh-CN', name: '中文（简体）' },
      { code: 'zh-TW', name: '中文（繁体）' },
      { code: 'en-US', name: 'English (US)' },
      { code: 'ja-JP', name: '日本語' },
      { code: 'ko-KR', name: '한국어' }
    ]
  }
  
  /**
   * 设置识别语言
   */
  setLanguage(lang) {
    if (!this.recognition) return false
    
    this.recognition.lang = lang
    return true
  }
  
  /**
   * 添加自定义命令
   */
  addCommand(action, keywords) {
    if (typeof keywords === 'string') {
      keywords = [keywords]
    }
    
    if (this.commandMappings[action]) {
      this.commandMappings[action].push(...keywords)
    } else {
      this.commandMappings[action] = keywords
    }
    
    console.log(`添加语音命令: ${action} -> ${keywords.join(', ')}`)
  }
  
  /**
   * 移除命令
   */
  removeCommand(action) {
    if (this.commandMappings[action]) {
      delete this.commandMappings[action]
      console.log(`移除语音命令: ${action}`)
    }
  }
  
  /**
   * 获取所有命令
   */
  getAllCommands() {
    return { ...this.commandMappings }
  }
  
  /**
   * 检查是否支持语音识别
   */
  isRecognitionSupported() {
    return this.isSupported && this.isInitialized
  }
  
  /**
   * 检查是否正在监听
   */
  isCurrentlyListening() {
    return this.isListening
  }
  
  /**
   * 获取设备权限状态
   */
  async getPermissionStatus() {
    if (typeof navigator !== 'undefined' && navigator.permissions) {
      try {
        const permission = await navigator.permissions.query({ name: 'microphone' })
        return permission.state
      } catch (error) {
        console.warn('无法获取麦克风权限状态:', error)
        return 'unknown'
      }
    }
    return 'unknown'
  }
  
  /**
   * 请求麦克风权限
   */
  async requestPermission() {
    try {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        stream.getTracks().forEach(track => track.stop())
        return 'granted'
      }
      return 'denied'
    } catch (error) {
      console.error('请求麦克风权限失败:', error)
      return 'denied'
    }
  }
  
  /**
   * 事件监听
   */
  on(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, [])
    }
    this.eventListeners.get(event).push(callback)
  }
  
  /**
   * 移除事件监听
   */
  off(event, callback) {
    if (this.eventListeners.has(event)) {
      const listeners = this.eventListeners.get(event)
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
      }
    }
  }
  
  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.eventListeners.has(event)) {
      this.eventListeners.get(event).forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('事件回调执行失败:', error)
        }
      })
    }
  }
  
  /**
   * 销毁语音识别
   */
  destroy() {
    if (this.isListening) {
      this.stopListening()
    }
    
    this.recognition = null
    this.eventListeners.clear()
    this.isInitialized = false
    this.isSupported = false
  }
}

// 创建单例实例
const speechRecognitionManager = new SpeechRecognitionManager()

export default speechRecognitionManager
